#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import socket
import struct
import subprocess

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 2006))
s.listen(2)
conn, addr = s.accept()

while True:
    command = conn.recv(1024)
    # 获取客户端发过来的命令，并执行返回结果
    res = subprocess.Popen(command.decode("utf-8"), shell=True,
                           stderr=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           )
    stdout = res.stdout.read()      # 这里的获取最好与命令的stdout err一致
    stderr = res.stderr.read()
    # 1、添加报头长度
    length = len(stdout) + len(stderr)
    command_length = struct.pack("i", length)
    # 2、发送报头
    conn.send(command_length)
    # 3、发送数据
    conn.sendall(stdout)
    conn.sendall(stderr)

conn.close()
